package com.me.study.concurrent.thread;

import java.util.Random;

/**
 * volatile 测试：t2 早了呢
 *
 * @author ME
 * @date 2019/1/29 11:38
 */
public class TestVolatile {

    public static void main(String[] args) {
        final VolatileExample example = new VolatileExample();
        Thread t1 = new Thread("t1") {
            @Override
            public void run() {
                example.writer();
                example.reader(Thread.currentThread().getName());
            }
        };
        Thread t2 = new Thread("t2") {
            @Override
            public void run() {
                example.reader(Thread.currentThread().getName());
            }
        };

        t1.start();
        t2.start();
    }

    public static class VolatileExample {
        private int a = 0;
        private volatile boolean flag = false;

        public void writer() {
            // SleepUtil.ms(500);

            a = new Random().nextInt(10); // [0, 10)
            flag = true;
        }

        public void reader(String theadName) {
            if (flag) {
                int i = a;
            }
            System.out.println(theadName + " [flag is: " + flag + ", and a is: " + a + "]");
        }
    }
}
